﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Windows.Media.Animation;
using System.ComponentModel;
using System.Threading;

namespace testMobi
{
    /// <summary>
    /// Interaction logic for Download.xaml
    /// </summary>
    public partial class Download : Page
    {
        private XDocument _doc = null;
        public XDocument Doc
        {
            get
            {
                if (_doc == null)
                    _doc = DownloadXml();

                return _doc;
            }
            set
            {
                _doc = value;
            }
        }

        BackgroundWorker _backgroundWorker = new BackgroundWorker();
        BackgroundWorker _backgroundWorkerExtraDownload = new BackgroundWorker();
        TimeSpan start;
        TimeSpan end;
        int minDownload = 5;
        bool errorOccured = false;//variable to catch error during downloading, to show proper exception

        public Download()
        {
            InitializeComponent();

            // Set up the Background Worker Events
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;
            _backgroundWorker.RunWorkerCompleted += 
                _backgroundWorker_RunWorkerCompleted;

            // Run the Background Worker
            _backgroundWorker.RunWorkerAsync();
        }


        // Worker Method
        void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            start = DateTime.Now.TimeOfDay;
            DownloadXml();
        }

        // Completed Method
        void _backgroundWorker_RunWorkerCompleted(
            object sender, 
            RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                //statusText.Text = "Cancelled";
            }
            else if (e.Error != null || errorOccured) 
            {
                //statusText.Text = "Exception Thrown";
                //MessageBox.Show("Check your internet connection or contact soft provider.");
                Application.Current.Shutdown();
            }
            else 
            {
                //statusText.Text = "Completed";
                end = DateTime.Now.TimeOfDay;
                TimeSpan duration = end - start;

                if (duration.Seconds > minDownload)
                    NavigateToApp();
                else
                {
                    _backgroundWorkerExtraDownload.DoWork += _backgroundWorkerExtraDownload_DoWork;
                    _backgroundWorkerExtraDownload.RunWorkerCompleted +=
                        _backgroundWorkerExtraDownload_RunWorkerCompleted;

                    _backgroundWorkerExtraDownload.RunWorkerAsync();
                    
                    //NavigateToApp();
                }
            }
        }

        void _backgroundWorkerExtraDownload_DoWork(object sender, DoWorkEventArgs e)
        {
            while (DateTime.Now.TimeOfDay < start.Add(new TimeSpan(0, 0, minDownload)))
            {
                //Do nothing...
            }
        }

        // Completed Method
        void _backgroundWorkerExtraDownload_RunWorkerCompleted(
            object sender,
            RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                //statusText.Text = "Cancelled";
            }
            else if (e.Error != null || errorOccured)
            {
                //statusText.Text = "Exception Thrown";
                //MessageBox.Show("Check your internet connection or contact soft provider.");
                Application.Current.Shutdown();
            }
            else
            {
                //statusText.Text = "Completed";
                
                NavigateToApp();
            }
        }

        private void NavigateToApp()
        {
            MenuPage page = new MenuPage();
            NavigationService nav = NavigationService.GetNavigationService(this);
            nav.Navigate(page);
        }


        private XDocument DownloadXml()
        {

            string baseurl = @"http://mobitee.com/getdata/dataupdate/?update=CountryList&platform=wphone7";
            string filename = "countrylist.xml";
            XDocument doc = new XDocument();

            try
            {
                
                WebClient Client = new WebClient();
                Client.DownloadFile(baseurl, filename);

                doc = XDocument.Load(filename);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while fetching the file" + filename + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                errorOccured = true;
            }

            
            ((App)Application.Current).Doc = doc;

            Doc = doc;
            return doc;
        }
    }
}
